from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views import View
from django.views.generic import ListView

from hr.forms import ResumeForm
from hr.models import Resume, Job, Delivery

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required


# Create your views here.
def send_sms(request):
    # 从表单中获取到电话号码
    phone = request.GET.get("phone")
    # 电话号码 放入 session 中
    request.session["sms_phone"] = phone

    # 获取验证码
    sms_code = get_sms_code()

    # TODO 通过短信平台发送短信

    # 短信验证码 放入 session 中
    request.session["sms_code"] = sms_code

    return JsonResponse({"code": sms_code})


# 生成验证码
def get_sms_code():
    import random
    check_code = ''
    for i in range(4):
        tep = random.randint(0, 9)
        check_code += str(tep)
    return check_code

def user_login(request):
    if request.method == 'GET':
        # GET请求方式直接渲染登录页
        return render(request, 'login.html')
    elif request.method == 'POST':
        # 获取表单中的数据
        phone = request.POST.get("phone")
        code = request.POST.get("phone_code")

        # 获取session中的数据
        phone_session = request.session.get("sms_phone", '')
        code_session = request.session.get("sms_code", '')

        # 判断表单数据与session数据 是否一致
        if phone == phone_session and code == code_session:
            # 判断用户是否注册(是否首次使用)
            isExist = User.objects.filter(username=phone).exists()
            if not isExist:  # 用户未注册(User表无记录)
                # 注册
                user = User.objects.create_user(username=phone, password=phone)
            else:  # 用户已注册(User表已有记录)
                # 登录
                user = authenticate(username=phone, password=phone)

            # 将用户对象保存到session中, 实现登录动作
            login(request, user)

            # 登录成功，跳转至岗位列表页面
            return redirect("search")
        else:
            # 登录失败
            return render(request, 'login.html', {'error': '手机号码与验证码不匹配'})

@method_decorator(login_required, name='dispatch')
class ResumeView(View):
    # GET请求
    def get(self, request):
        # 查询当前用户下的简历
        resumes = Resume.objects.filter(user=request.user)

        resume_exist = None
        if resumes.count() > 0:
            resume_exist = resumes.first() # 默认使用第一份简历

        return render(request, 'resume.html', {'resume': resume_exist})

    # POST请求
    def post(self, request):
        # 使用表单数据创建Form对象
        resume_form = ResumeForm(request.POST)

        # 使用Form对象验证表单数据
        if resume_form.is_valid():
            # 表单验证通过
            id = request.POST.get("id")
            if id != '': # 根据表单的id 是否为空 判断 新增或更新 操作
                # 更新操作
                resume_exist = Resume.objects.get(pk=id)
                resume_form = ResumeForm(request.POST, instance=resume_exist)
            resume = resume_form.save(commit=False) # 使用表单数据创建简历对象
            resume.user = request.user # 简历绑定当前用户对象
            resume.save() # 保存简历对象
            return render(request, 'resume.html', {'msg': "简历保存成功", 'resume': resume})

        else:
            # 表单验证未通过
            return render(request, 'resume.html', {'resume': resume_form.data, 'form': resume_form})

# 查询职位列表
def search_jobs(request):
    job_list = Job.objects.all().order_by('-id')
    paginator = Paginator(job_list, 3) # 使用Django分页器组件实现分页
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    return render(request, 'joblist.html', {'page_obj': page_obj})

def job_detail(request, pk):
    detail = Job.objects.get(pk=pk)
    return render(request, 'job.html', {'job': detail})

def presented(request, job_id):
    if not request.user.id:
        return JsonResponse({'code': 403, 'msg': '您尚未登录,请登录后再申请!'})

    # 查询当前用户下的简历
    resumes = Resume.objects.filter(user=request.user)

    if resumes.count() > 0:
        resume_exist = resumes.first()  # 默认使用第一份简历
        Delivery.objects.create(job_id=job_id, resume=resume_exist, state='已投递')
        return JsonResponse({'code': 200, 'msg': '简历投递成功'})
    else:
        return JsonResponse({'code': 404, 'msg': '您尚无简历,请填写简历后申请!'})

# 简历投递岗位记录列表
class DeliveryList(ListView):
    template_name = 'delivery.html'
    context_object_name = 'delivery_list'

    # 重写查询结果集
    def get_queryset(self):
        # 获得当前用户简历对象
        user_resume = Resume.objects.filter(user=self.request.user)[0]
        # 通过简历对象获取投递岗位记录
        dlivery_queryset = Delivery.objects.filter(resume=user_resume)
        # 返回投递岗位记录查询结果集
        return dlivery_queryset
